﻿// Audiobooks.cpp : 实现文件
//

#include "stdafx.h"
#include "TeacherManager.h"
#include "SmartTransfer.h"
#include "Audiobooks.h"
#include "afxdialogex.h"
#include "CommonFunction.h"
#include "QuanWenFanyi.h"
#include "LangduWordTranslate.h"
#include "YouShengWenZhangTingXie.h"
#include "Recite.h"
//#include "DanJuFanYi.h"


int All_i=0;
CString str_GenDu;
// CAudiobooks 对话框
BOOL JinDuTiao1 = TRUE;
HTREEITEM hCataItem1;


IMPLEMENT_DYNAMIC(CAudiobooks, CDialogEx)

    CAudiobooks::CAudiobooks(CWnd* pParent /*=NULL*/)
    : CDialogEx(CAudiobooks::IDD, pParent)
{
    m_iMaxRange = 0;
    m_iReadInfoIndex = 0;
    m_bCanReadNext = true;
    m_iRecordMs = 0;
    m_bIsRecorded = FALSE;
}

CAudiobooks::~CAudiobooks()
{
}

void CAudiobooks::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_BUTTON19, m_langdu);
    DDX_Control(pDX, IDC_BUTTON6, m_stop);
    DDX_Control(pDX, IDC_BUTTON18, m_chongfu_ss);
    DDX_Control(pDX, IDC_BUTTON5, m_mp3);
    DDX_Control(pDX, IDC_BUTTON26, m_gendu);
    DDX_Control(pDX, IDC_BUTTON22, m_end);
    DDX_Control(pDX, IDC_BUTTON25, m_chongfugendu);
    DDX_Control(pDX, IDC_BUTTON21, m_playsound);
    DDX_Control(pDX, IDC_BUTTON1, m_dancifanyi);
    DDX_Control(pDX, IDC_BUTTON2, m_quanwenfanyi);
    DDX_Control(pDX, IDC_BUTTON3, m_danjufanyi);
    DDX_Control(pDX, IDC_BUTTON4, m_tingxiewenzhang);
    DDX_Control(pDX, IDC_COMBO1, m_readselectbox);
    DDX_Control(pDX, IDC_MFCFONTCOMBO1, m_fontstylecombo);
    DDX_Control(pDX, IDC_SCROLLBAR1, m_readspeedscrollbar);
    DDX_Control(pDX, IDC_SCROLLBAR2, m_readdiffficultyscrollbar);
    DDX_Control(pDX, IDC_TREE1, m_Tree);
    DDX_Control(pDX, IDC_COMBO3, m_zihaocombox);
    DDX_Control(pDX, IDC_AUDIOBOOKEDIT, m_Edit);
    DDX_Control(pDX, IDC_BUTTON7, m_SuCai);
    DDX_Control(pDX, IDC_BUTTON7, m_SuCai);
    DDX_Control(pDX, IDC_PROGRESS1, m_JinDuTiao);
    DDX_Control(pDX, IDC_STATIC222, m_Static222);
    DDX_Control(pDX, IDC_BUTTON8, m_ButtonBeiSong);
    DDX_Control(pDX, IDC_BUTTON8, m_ButtonBeiSong);
}


BEGIN_MESSAGE_MAP(CAudiobooks, CDialogEx)
    ON_WM_CLOSE()
    //ON_WM_LBUTTONDOWN()
    ON_BN_CLICKED(IDC_BUTTON19, &CAudiobooks::OnBnClickedButton19)
    ON_BN_CLICKED(IDC_BUTTON6, &CAudiobooks::OnBnClickedButton6)
    ON_BN_CLICKED(IDC_BUTTON3, &CAudiobooks::OnBnClickedButton3)
    ON_BN_CLICKED(IDC_BUTTON4, &CAudiobooks::OnBnClickedButton4)
    ON_BN_CLICKED(IDC_BUTTON2, &CAudiobooks::OnBnClickedButton2)
    ON_BN_CLICKED(IDC_BUTTON1, &CAudiobooks::OnBnClickedButton1)
    ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, &CAudiobooks::OnSelchangedTree1)
    ON_WM_HSCROLL()
    ON_BN_CLICKED(IDC_BUTTON7, &CAudiobooks::OnBnClickedButton7)
    ON_BN_CLICKED(IDC_BUTTON5, &CAudiobooks::OnBnClickedButton5)
    ON_BN_CLICKED(IDC_BUTTON26, &CAudiobooks::OnBnClickedButton26)
    ON_BN_CLICKED(IDC_BUTTON22, &CAudiobooks::OnBnClickedButton22)
    ON_BN_CLICKED(IDC_BUTTON21, &CAudiobooks::OnBnClickedButton21)

    ON_CBN_SELCHANGE(IDC_MFCFONTCOMBO1, &CAudiobooks::OnCbnSelchangeZiTi)
    ON_CBN_SELCHANGE(IDC_COMBO3, &CAudiobooks::OnCbnSelchangeZiHao)
    ON_WM_CTLCOLOR()
    ON_WM_PAINT()
    ON_BN_CLICKED(IDC_BUTTON8, &CAudiobooks::OnBnClickedButton8)
    ON_BN_CLICKED(IDC_BUTTON18, &CAudiobooks::OnBnClickedButton18)
    ON_BN_CLICKED(IDC_BUTTON25, &CAudiobooks::OnBnClickedButton25)
    ON_BN_CLICKED(IDC_BUTTON10, &CAudiobooks::OnBnClickedButton10)
    ON_WM_TIMER()
    ON_BN_CLICKED(IDC_BUTTON_DEL_FILE, &CAudiobooks::OnBnClickedButtonDelFile)
    ON_NOTIFY(NM_CLICK, IDC_TREE1, &CAudiobooks::OnNMClickTree1)
    ON_MESSAGE(WM_TTSAPPCUSTOMEVENT, &CAudiobooks::OnTTSHandleEvent)
    ON_MESSAGE(MM_MCINOTIFY, &CAudiobooks::OnMciNotify)
END_MESSAGE_MAP()

// CAudiobooks 消息处理程序


BOOL CAudiobooks::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    m_nReadCurrentCursor = 0;

    m_nReadMode = E_READ_ARTICLE;
    //初始化树 
    HTREEITEM hRoot;     // 树的根节点的句柄   
    HTREEITEM hCataItem; // 可表示任一分类节点的句柄   
    HTREEITEM hArtItem;  // 可表示任一文章节点的句柄  

    hRoot = m_Tree.InsertItem(_T(""), 0, 0); 
    hCataItem = m_Tree.InsertItem(_T("素材库"), 1, 1, hRoot, TVI_LAST); 
    m_Tree.SetItemData(hCataItem, 1);	
    hCataItem1 = hCataItem;
    hArtItem = m_Tree.InsertItem(_T("添加我的素材库"), 1, 2, hCataItem, TVI_LAST);
    m_Tree.SetItemData(hArtItem,  (DWORD_PTR)hArtItem);

    _RecordsetPtr pRecSet =	theApp.m_MyDbFun.GetTablesBySql(_T("select * from Table_NovelCategory"));
    try
    {
        _variant_t CategoryName;
        _variant_t NovelId;

        CString strtemp;
        while(!pRecSet->adoEOF)
        {
            //GradeID = pRecSet->GetCollect(_variant_t((long)0));
            //取得第1列的值，从0开始计数，你也可以直接列出列的名称，如下一行

            CategoryName = pRecSet->GetCollect("CategoryName");
            if(CategoryName.vt != VT_NULL)
            {
                strtemp = (LPCTSTR)(_bstr_t)CategoryName;
            }

			if(strtemp.Find(_T("新概念英语")) == 0){
				pRecSet->MoveNext();
				continue;
			}
            hCataItem = m_Tree.InsertItem(strtemp, 1, 1, hRoot, TVI_LAST);   

            m_Tree.SetItemData(hCataItem, 1);

            NovelId = pRecSet->GetCollect("CategoryId");
            int iNovelId = 0;
            if (NovelId.vt != VT_NULL)
            {
                iNovelId = NovelId.intVal;
            }

            CString SqlStr;
            SqlStr.Format(_T("select * from Table_Novel where NovelCategory = %d"), iNovelId);

            _RecordsetPtr pNameRecSet =	theApp.m_MyDbFun.GetTablesBySql(SqlStr.GetString());

            _variant_t NovalNameCN;
            CString strName;
            while(!pNameRecSet->adoEOF)
            {
                NovalNameCN = pNameRecSet->GetCollect("NovelNameCN");
                CString Tmp;
                if(NovalNameCN.vt != VT_NULL)
                {
                    Tmp = (LPCTSTR)(_bstr_t)NovalNameCN;
                }

                hArtItem = m_Tree.InsertItem(Tmp, 1, 2, hCataItem, TVI_LAST);   

                m_Tree.SetItemData(hArtItem,  (DWORD_PTR)hArtItem);
                pNameRecSet->MoveNext();
            }
            pNameRecSet->Close();
            pNameRecSet = NULL;

            pRecSet->MoveNext();			
        }
        MyExpandTree(m_Tree.GetRootItem());			
    }
    catch(_com_error &e)
    {
        AfxMessageBox(e.Description());
        return FALSE;
    }

    pRecSet->Close();
    pRecSet = NULL;

    CenterWindow(GetDesktopWindow());

    m_hBitmap = LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP4));     
    _WaveInit(&m_WaveObject,GetDlgItem(IDC_STATIC1)->GetSafeHwnd(),m_hBitmap,30,0);    
    _WaveEffect(&m_WaveObject,1,4,2,180); 

    ModifyStyleEx(WS_EX_TOOLWINDOW, WS_EX_APPWINDOW);
    HICON m_hIcon;  
    m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
    SetIcon(m_hIcon, TRUE);  
    SetIcon(m_hIcon, FALSE); 

    //////////////////////////////////////////////////////////////////////////

    HRESULT Hr = theApp.m_pSpVoice->SetNotifyWindowMessage(GetSafeHwnd(), WM_TTSAPPCUSTOMEVENT, 0, 0);
    // We're interested in all TTS events
    if( FAILED(Hr) )
    {
        MyAfxMessageBox(_T("打开TTS_Notify失败！"));
        return FALSE;
    }

    Hr = theApp.m_pSpVoice->SetInterest( SPFEI_ALL_TTS_EVENTS, SPFEI_ALL_TTS_EVENTS );
    if( FAILED(Hr) )
    {
        MyAfxMessageBox(_T("打开TTS_Interest失败！"));
        return FALSE;
    }

    //////////////////////////////////////////////////

    m_dancifanyi.LoadStdImage(IDB_PNG64, _T("PNG"));
    m_danjufanyi.LoadStdImage(IDB_PNG65, _T("PNG"));
    m_quanwenfanyi.LoadStdImage(IDB_PNG66, _T("PNG"));
    m_tingxiewenzhang.LoadStdImage(IDB_PNG67, _T("PNG"));

    m_langdu.LoadStdImage(IDB_PNG49, _T("PNG"));
    m_stop.LoadStdImage(IDB_PNG50, _T("PNG"));
    m_stop.EnableButton(FALSE);
    m_chongfu_ss.LoadStdImage(IDB_PNG51, _T("PNG"));
    //m_chongfu_ss.EnableButton(FALSE);
    m_mp3.LoadStdImage(IDB_PNG52, _T("PNG"));
    ///////////////////////////////////////////////
    m_gendu.LoadStdImage(IDB_PNG53, _T("PNG"));

    m_end.LoadStdImage(IDB_PNG54, _T("PNG"));
    m_end.EnableButton(FALSE);

    m_chongfugendu.LoadStdImage(IDB_PNG55, _T("PNG"));
    //m_chongfugendu.EnableButton(FALSE);
    SetButtonStatus(IDC_BUTTON25, TRUE);


    m_playsound.LoadStdImage(IDB_PNG56, _T("PNG"));
    m_playsound.EnableButton(FALSE);

    m_SuCai.LoadStdImage(IDB_PNG156, _T("PNG"));

    m_ButtonBeiSong.LoadStdImage(IDB_PNG159,_T("PNG"));

    theApp.InitReadList(m_readselectbox, _T("美音女声"));

    //字号初始化
    CString strIndex;
    for (int i = 0; i < 22; ++i)
    {
        strIndex.Format(_T("%d"), i + 9); //字号从9 开始
        m_zihaocombox.InsertString(i, strIndex.GetString());
    }

    m_zihaocombox.SetCurSel(3);

    //m_fontstylecombo
    int ifontcount = m_fontstylecombo.GetCount();
    for (int i = 0; i < ifontcount; i++)
    {
        CString fontname;
        m_fontstylecombo.GetLBText(i, fontname);
        if ((fontname == _T("arial")) || (fontname == _T("Arial")))
        {
            m_fontstylecombo.SetCurSel(i);
        }
    }

    m_strFirstShowNovelName = _T("我们该选择死亡吗");
    CString NovelContent = GetNovelContentByNovelName(m_strFirstShowNovelName, true);

    m_editFont.CreatePointFont(100, _T("宋体"));   //设置字体 
    GetDlgItem(IDC_STATIC_NOVEL_TITEL)->SetFont(&m_editFont);  //告知文本框显示的字体

    CString strTitle = _T("素材库-") + m_strFirstShowNovelName;
    SetDlgItemText(IDC_STATIC_NOVEL_TITEL, strTitle.GetString());

    m_editFont.CreatePointFont(120, _T("Arial"));  
    GetDlgItem(IDC_AUDIOBOOKEDIT)->SetFont(&m_editFont); 
    SetDlgItemText(IDC_AUDIOBOOKEDIT, NovelContent.GetString());

    m_readspeedscrollbar.SetScrollRange(0, 20);
    m_readspeedscrollbar.SetScrollPos(9);
    SetDlgItemInt(IDC_READ_SPEED, -1);

    m_readdiffficultyscrollbar.SetScrollRange(1,6);
    m_readdiffficultyscrollbar.SetScrollPos(4);
    SetDlgItemInt(IDC_READ_DIFFICULTY, 4);	
    GetDlgItem(IDC_PROGRESS1)->ShowWindow(FALSE);
    GetDlgItem(IDC_STATIC222)->ShowWindow(FALSE);

    UpdateWindow();

    return TRUE;  // return TRUE unless you set the focus to a control
    // 异常: OCX 属性页应返回 FALSE
}

//void SetReadRelatedButtonStatus(BOOL bButtonStatus)

void CAudiobooks::SetDefautCharFormat()
{
    memset(&m_cfDefault,   0,   sizeof(m_cfDefault));   

    m_cfDefault.cbSize   =   sizeof(CHARFORMAT);   

    m_cfDefault.dwMask   =   CFM_BOLD   |   CFM_COLOR   |   CFM_FACE   |   CFM_ITALIC   |   CFM_SIZE   |   CFM_STRIKEOUT  /* |   CFM_UNDERLINE*/;   

    m_cfDefault.crTextColor   =   RGB(255,   0,   0);//颜色   

    _tcscpy_s(m_cfDefault.szFaceName,   _T("宋体"));//字体   

    m_cfDefault.bPitchAndFamily   =   FF_SWISS;
    m_cfDefault.yHeight   =   260; 

}

void CAudiobooks::OnClose()
{
    _WaveFree(&m_WaveObject);  
    OnBnClickedButton6();
    theApp.StopSpeak();
    theApp.SpeechRecognition_Stop(theApp.m_strCommonWaveFile);	
    CDialogEx::OnClose();
}

//朗读
void CAudiobooks::OnBnClickedButton19() 
{	
    //获取当前鼠标前后的内容
    m_nReadMode = E_READ_ARTICLE;

    CString strInfo;
    int iPos = 0;
    GetReadInfo(iPos, strInfo);

    //m_langdu.LoadStdImage(IDB_PNG_LANGDU_HOT, _T("PNG"));

    KillTimer(TIMER_AUDIO_BOOK_On_Read);
    All_i = iPos/70;
    m_Edit.LineScroll(All_i);
    m_Edit.SetScrollPos(SB_VERT,iPos);

    Invalidate();
    SetButtonStatus(IDC_BUTTON6, TRUE); //停止
    SetButtonStatus(IDC_BUTTON5, FALSE); //转换成MP3
    SetButtonStatus(IDC_BUTTON18, FALSE);
    SetButtonStatus(IDC_BUTTON19, FALSE);

    SetReadRelatedButtonStatus(FALSE);	
    UpdateData(FALSE);

    theApp.m_pSpVoice->Resume();
    CString strLangDuZhe;
    GetDlgItemText(IDC_COMBO1, strLangDuZhe);
    int iSpead = m_readspeedscrollbar.GetScrollPos( ) - 10;
    CString strLangDuSuDu;
    strLangDuSuDu.Format(_T("%d"), iSpead);
    theApp.SetVoiceRateByValue(strLangDuZhe, strLangDuSuDu);

    if(strInfo.IsEmpty())
    {
        MessageBox(_T("朗读内容不能为空!"), _T("提示"), MB_OK|MB_ICONWARNING);
        return;
    }
    //SetTimer(TIMER_AUDIO_BOOK_On_Read, 35000, NULL);
    strInfo.Replace(_T("\r\n"), _T(" "));
    theApp.Speak(strInfo, SPF_ASYNC);
    int iDelay = (strInfo.GetLength()/13 + 1)*1000;
    //SetTimer(TIMER_AUDIO_BOOK_READ_END, iDelay, NULL);
}


void CAudiobooks::GetReadInfo(int &iPos, CString &strInfo)
{
    int iStart = 0;
    int iEnd = 0;

    CString strEdit1;
    GetDlgItemText(IDC_AUDIOBOOKEDIT, strEdit1); // 获取指定ID的编辑框内容	
    ((CEdit*)(GetDlgItem(IDC_AUDIOBOOKEDIT)))->GetSel(iStart, iEnd);
    CString strHead = strEdit1.Left(iStart);
    CString strEnd = strEdit1.Right(strEdit1.GetLength() - iStart);
    int iDouHao = strHead.ReverseFind(_T(','));
    int iJuHao = strHead.ReverseFind(_T('.'));
    int iWenHao = strHead.ReverseFind(_T('?'));
    int iFeiHao = strHead.ReverseFind(_T(';'));
    iPos = max(iDouHao, iJuHao);
    iPos = max(iPos, iWenHao);
    iPos = max(iPos, iFeiHao);
    iPos += 1;
    strInfo = strEdit1.Right(strEdit1.GetLength() - iPos);
    m_nReadCurrentCursor = iPos;

    strHead = strEdit1.Left(iPos);
    int nPos = strHead.Find(_T("\r\n"), 0);
    while (nPos >= 0 )
    {
        m_nReadCurrentCursor -= 1;
        nPos = strHead.Find(_T("\r\n"), nPos+1); 
    }

}

void CAudiobooks::OnBnClickedButton6()//停止
{
    KillTimer(TIMER_AUDIO_BOOK_On_Read);
    m_Edit.SetSel(0,0);
    m_Edit.LineScroll(0);
    m_Edit.SetScrollPos(SB_VERT,0);
    Invalidate();
    SetButtonStatus(IDC_BUTTON6, FALSE);
    SetButtonStatus(IDC_BUTTON18, TRUE);
    SetButtonStatus(IDC_BUTTON19, TRUE);
    SetButtonStatus(IDC_BUTTON5, TRUE);
    SetReadRelatedButtonStatus(TRUE);
    UpdateWindow();

    theApp.StopSpeak();
    UpdateWindow();
}

//单句翻译
void CAudiobooks::OnBnClickedButton3()
{
    // TODO: 在此添加控件通知处理程序代码

    CString strInfo = m_Edit.GetSelText();
    if (strInfo.IsEmpty())
    {
        MyAfxMessageBox(_T("请选中一句，然后再试，谢谢！"));
        return;
    }	

    CSmartTransfer dlg;
    dlg.m_strRawText = strInfo;
    dlg.DoModal();

    //CDanJuFanYi FanYiObj;
    //FanYiObj.m_strSentence = strInfo;
    //FanYiObj.CenterWindow();
    //FanYiObj.DoModal();
}

//听写文章
void CAudiobooks::OnBnClickedButton4()
{
    // TODO: 在此添加控件通知处理程序代码
    OnBnClickedButton22();

    CYouShengWenZhangTingXie wenzhang;
    CString strEdit1;
    GetDlgItemText(IDC_AUDIOBOOKEDIT, strEdit1); // 获取指定ID的编辑框内容
    wenzhang.m_ListWenZhang = strEdit1;
    wenzhang.DoModal();
}

//全文翻译
void CAudiobooks::OnBnClickedButton2()
{
    // TODO: 在此添加控件通知处理程序代码
    HTREEITEM selItem;
    CString NovelContent;
    selItem = m_Tree.GetSelectedItem();
    CString NovelName = m_Tree.GetItemText(selItem);
    if (NovelName.IsEmpty())
    {
        if (!m_strFirstShowNovelName.IsEmpty())
        {
            NovelName = m_strFirstShowNovelName;
        }
        else
        {
            MyAfxMessageBox(_T("没有读物被选中，请选中后再试！"));
            return;
        }
    }

    NovelContent = GetNovelContentByNovelName(NovelName, false);
    if (NovelContent.IsEmpty())
    {
        NovelContent = _T("暂无中文");
    }	

    CQuanWenFanYi dlg;
    dlg.NovelContentCN = NovelContent;
    dlg.m_strZiTi = _T("宋体");
    GetDlgItemText(IDC_COMBO3, dlg.m_strZiHao);
    dlg.DoModal();

    return;	
}

//单词翻译
void CAudiobooks::OnBnClickedButton1()
{
    // TODO: 在此添加控件通知处理程序代码
    CLangduWordTranslate langdu;
    int iStart = 0;
    int iEnd = 0;
    CString strContent;
    CString strSql;
    GetDlgItemText(IDC_AUDIOBOOKEDIT,strContent);
    strContent.Remove('\n');
    ((CEdit*)(GetDlgItem(IDC_AUDIOBOOKEDIT)))->GetSel(iStart, iEnd); 
    if (iStart == iEnd)
    {
        MessageBox(_T("请选中文本框中相关信息"));
        return;
    }
    CString strInfo = strContent.Right(strContent.GetLength() - (iStart));
    strInfo.Truncate(iEnd -iStart);

    strSql.Format(_T("SELECT ChineseMeaning  FROM  Table_Word where EnglishWord = '%s'"),strInfo);
    _RecordsetPtr pRecSet =	theApp.m_MyDbFun.GetTablesBySql(strSql.GetString());
    _variant_t vit = pRecSet->GetCollect(_variant_t((long)0));
    if (NULL == pRecSet)
    {
        MessageBox(_T("没有找到"));
        return; 
    }
    CString id = vit;
    langdu.m_Str1 = strInfo;
    langdu.m_Str =  id;
    CString strText(_T(""));
    m_readselectbox.GetLBText(m_readselectbox.GetCurSel(),strText);
    langdu.strLangDuZhe = strText;
    langdu.DoModal();
}

CString CAudiobooks::GetNovelContentByNovelName(CString &NovelName, bool bIsEN)
{
    CString strtemp = _T("");
    TCHAR   szCause[255];

    CString strTitle;
    strTitle.Format(_T("素材库-%s"), NovelName.GetString() );
    SetDlgItemText(IDC_STATIC_NOVEL_TITEL, strTitle.GetString());

    //根据文章名在 Table_Novel 中找文章id
    CString strSql;
    strSql.Format(_T("select NovelId from Table_Novel where NovelNameCN = '%s'"),  NovelName.GetString());
    _RecordsetPtr pRecSet =	theApp.m_MyDbFun.GetTablesBySql(strSql.GetString());

    if (NULL == pRecSet)
    {
        //选中了树的大节点,例如 "寓言"/"笑话"等，查询不到信息，返回
        return strtemp;
    }

    try
    {		
        _variant_t NovelId;

        while(!pRecSet->adoEOF)
        {
            NovelId = pRecSet->GetCollect("NovelId");
            int Tmp = 0;
            if(NovelId.vt != VT_NULL)
            {
                Tmp = NovelId.intVal;
            }	

            //根据文章 id 在 Table_NovelContent 中找文章内容（ContentEN）
            _variant_t NovelContent;
            if (bIsEN)
            {
                strSql.Format(_T("Select ContentEN from Table_NovelContent where NovelID = %d"), Tmp);
            }
            else
            {
                strSql.Format(_T("Select ContentCN from Table_NovelContent where NovelID = %d"), Tmp);
            }

            _RecordsetPtr pContentSet =	theApp.m_MyDbFun.GetTablesBySql(strSql.GetString());
            if (NULL == pContentSet)
            {
                //没有查询到信息
                MyAfxMessageBox(_T("没有 '%s' 对应的文章"), NovelName.GetString());
                return strtemp;
            }
            while (!pContentSet->adoEOF)
            {
                //NovelContent = pContentSet->GetCollect("ContentEN");
                if (bIsEN)
                {
                    NovelContent = pContentSet->GetCollect("ContentEN");
                }
                else
                {
                    NovelContent = pContentSet->GetCollect("ContentCN");
                }

                if (NovelContent.vt != NULL)
                {
                    SAFEARRAY *pArray = NovelContent.parray;

                    //字符总个数
                    ULONG ulLength = NovelContent.parray->rgsabound->cElements;
                    //LONG lLbound = NovelContent.parray->rgsabound->lLbound; //最小下标
                    unsigned char *pData = NULL;
                    SafeArrayAccessData(pArray, (void HUGEP **)&pData);
                    CString strContent;
                    //strContent.AppendFormat(_T("%s"), pData);
                    strContent = pData;
                    //去掉末尾多余的字符
                    strtemp = strContent.Left(ulLength); 
                    SafeArrayUnaccessData(pArray);
                    break;					
                }

                pContentSet->MoveNext();
            }

            pContentSet->Close();
            pContentSet = NULL;

            pRecSet->MoveNext();
        }

        pRecSet->Close();
        pRecSet = NULL;
    }
    catch (CMemoryException* e)
    {
        e->GetErrorMessage(szCause, 255);
        MyAfxMessageBox(_T("Memory exception.Error:%s"), szCause);
    }
    catch (CFileException* e)
    {
        MyAfxMessageBox(_T("File operation exception, cause %d"), e->m_cause);
    }
    catch (CException* e)
    {
        e->GetErrorMessage(szCause, 255);

        MyAfxMessageBox(_T("Other  exception.Error:%s"), szCause);
    }

    //strtemp.Replace(_T("\r\n"), _T(" "));

    return strtemp;
}

void CAudiobooks::OnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
    //切换文本框信息前关闭朗读
    

    LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
    HTREEITEM selItem;
    //获得选择项
    selItem = m_Tree.GetSelectedItem();
    CString NovelName = m_Tree.GetItemText(selItem);
    if (NovelName.IsEmpty())
    {
        //窗口初始化时，NovelName为空，不处理这个请求，直接返回
        return;
    }

    OnBnClickedButton22();
    SetButtonStatus(IDC_BUTTON21, FALSE);

    //if(NovelName == _T("添加我的素材库"))
    //    {
    //    //添加打开素材库的代码
    //    OnBnClickedButton7();
    //    //m_Tree.SelectItem(m_Tree.GetParentItem(selItem));
    //    }
    for(map<HTREEITEM, sEssary>::iterator it = m_itreeData.begin(); it != m_itreeData.end(); it++)
    {

        if(it->first == selItem)
            //if( it->second.NovelName.compare(NovelName)==0)

        {
            CString  str = it->second.ContenEN;
            GetDlgItem(IDC_AUDIOBOOKEDIT)->SetWindowText(str.GetString());   //EDIT控件显示数据
            return;
        }
    }
    CString  strtemp = GetNovelContentByNovelName(NovelName);

    //查询到的内容填写到文本框中
    if (!strtemp.IsEmpty())
    {
        CString strZiTi;
        CString strTitle;
        strTitle.Format(_T("素材库-%s"), NovelName.GetString() );
        SetDlgItemText(IDC_STATIC_NOVEL_TITEL, strTitle.GetString());
        GetDlgItemText(IDC_MFCFONTCOMBO1, strZiTi);
        if (!strZiTi.IsEmpty())
        {
            CString strZiHao;
            GetDlgItemText(IDC_COMBO3, strZiHao);
            if (!strZiHao.IsEmpty())
            {
                int iZiHao = _tstoi(LPCTSTR(strZiHao))*10;
                //char *p = (LPSTR)(LPCTSTR)strZiHao; 
                //int iZiHao = atoi(p);
                m_editFont.CreatePointFont(iZiHao, strZiTi.GetString()); 
            }
        }	

        GetDlgItem(IDC_AUDIOBOOKEDIT)->SetFont(&m_editFont); 
        SetDlgItemText(IDC_AUDIOBOOKEDIT, strtemp.GetString());
    }
    // TODO: 在此添加控件通知处理程序代码
    //选定文件后，将文件内容显示在文本框中。

    if (E_FOLLOWME_NEXT_SENT == m_nReadMode)
    {
        m_nReadMode = E_UNKNOWN_TYPE;
    }

    *pResult = 0;
}


void CAudiobooks::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
    CWnd *pReadSpeed = GetDlgItem(IDC_SCROLLBAR1);
    CWnd *pReadDifficulty = GetDlgItem(IDC_SCROLLBAR2);
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    if (pReadSpeed == pScrollBar)
    {
        int pos = m_readspeedscrollbar.GetScrollPos();
        switch (nSBCode)   
        {   
            // 如果向左滚动一列，则pos减1  
        case SB_LINELEFT:   
            pos -= 1;  

            break;   
            // 如果向右滚动一列，则pos加1  
        case SB_LINERIGHT:   
            pos  += 1; 
            break;  
            // 如果滚动到最左端  
        case SB_LEFT:   
            pos = 0;   
            break;   
            // 如果滚动到最右端
        case SB_RIGHT:   
            pos = 20;   
            break;     
            // 如果拖动滚动块滚动到指定位置，则pos赋值为nPos的值  
        case SB_THUMBPOSITION:   
            pos = nPos;   
            break;   
            // 下面的m_horiScrollbar.SetScrollPos(pos);执行时会第二次进入此函数，最终确定滚动块位置，并且会直接到default分支，所以在此处设置编辑框中显示数值  
        default:   
            //SetDlgItemInt(IDC_READSPEED, pos);  
            break;   
        } 

        //CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);  
        pos = m_readspeedscrollbar.GetScrollPos();

        //位置值再做一次修正
        if (pos > 20)
        {
            pos = 20;
        }
        if (pos < 0)
        {
            pos = 0;
        }

        pos = pos - 10;

        SetDlgItemInt(IDC_READ_SPEED, pos);
    }

    if (pReadDifficulty == pScrollBar)
    {
        int pos = m_readdiffficultyscrollbar.GetScrollPos();
        switch (nSBCode)   
        {   
            // 如果向左滚动一列，则pos减1  
        case SB_LINELEFT:   
            pos -= 1; 
            break;   
            // 如果向右滚动一列，则pos加1  
        case SB_LINERIGHT:   
            pos  += 1; 

            break;  
            // 如果滚动到最左端  
        case SB_LEFT:   
            pos = 0;   
            break;   
            // 如果滚动到最右端
        case SB_RIGHT:   
            pos = 6;   
            break;     
            // 如果拖动滚动块滚动到指定位置，则pos赋值为nPos的值  
        case SB_THUMBPOSITION:   
            pos = nPos;   
            break;   
            // 下面的m_horiScrollbar.SetScrollPos(pos);执行时会第二次进入此函数，最终确定滚动块位置，并且会直接到default分支，所以在此处设置编辑框中显示数值  
        default:   
            //SetDlgItemInt(IDC_READSPEED, pos);  
            break;   
        } 

        //CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);  
        pos = m_readdiffficultyscrollbar.GetScrollPos();

        //位置值再做一次修正
        if (pos > 6)
        {
            pos = 6;
        }
        if (pos < 1)
        {
            pos = 1;
        }

        SetDlgItemInt(IDC_READ_DIFFICULTY, pos);
    }
    //CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);  


    /*int iSpeed = m_readspeedscrollbar.GetScrollPos();
    iSpeed = iSpeed - 10;
    SetDlgItemInt(IDC_READ_SPEED, iSpeed);

    int iDifficulty = m_readdiffficultyscrollbar.GetScrollPos();
    SetDlgItemInt(IDC_READ_DIFFICULTY, iDifficulty);*/

    CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar);  

    return;	
}

//打开我的素材库
void CAudiobooks::OnBnClickedButton7()
{
    // TODO: 在此添加控件通知处理程序代码
    int n=0;
    int n1=0;
    CString DiZhi ;
    CString WenJianMing ;
    CString tmp;
    CFileDialog dlg(TRUE,_T(""),_T(""),
        OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
        _T("(File(*.txt)|*.txt|(*.doc)|*.doc|"));
    if (dlg.DoModal())
    {
        m_strFilePathName = dlg.GetPathName();
        if (m_strFilePathName.IsEmpty())
        {
            return; //用户取消了本次操作
        }
    }

    //m_strFilePathName 文件名及路径


    for(int i=0; i < m_strFilePathName.GetLength();i++)
    {
        if(m_strFilePathName[i] == '\\' )
        {
            n++;
        }
    }
    for(int i=0; i< m_strFilePathName.GetLength();i++)
    {
        if(m_strFilePathName[i] == '\\' )
        {
            n1++;
        }
        if(n1 == n )
        {
            WenJianMing += m_strFilePathName[i+1];
        }
        if(n != n1)
        {
            DiZhi += m_strFilePathName[i];
        }
    }
    CFile file;    
    //static int position = 0;
    int position = 0;
    file.Open(m_strFilePathName, CFile::modeRead);

    unsigned char  s2; 
    file.Read(&s2,sizeof(s2));
    int p = s2<<8;
    file.Read(&s2,sizeof(s2));
    p += s2;

    int nEncode = 0;
    switch(p)  
    {  
    case 0xefbb:
        nEncode = 1;
        //AfxMessageBox("UTF-8");  
        break;  
    case 0xfffe:
        nEncode = 2;
        //AfxMessageBox("unicode Big Endian格式");  
        break;  
    case 0xfeff:
        nEncode = 3;
        //AfxMessageBox("unicode格式");  
        break;         
    default:
        nEncode = 4; //ANSI
        break;  
    }

    while (true)    
    {   
        char ReadBuf[260]={0};
        wchar_t wsReadBuf[1024] = {0};
        // 移动文件指针    
        file.Seek(position, CFile::begin);    
        // 读取文件数据    
        int ret = file.Read(ReadBuf, 256);    
        position += ret;
        if (nEncode == 1)
        {
            MultiByteToWideChar(CP_UTF8, 0, ReadBuf, -1, wsReadBuf, ret);
            tmp += wsReadBuf;
        } else {
            tmp += ReadBuf;
        }
        
        // 如果到达文件结尾则中止循环    
        if (ret < 256)    
            break;    
    } 
    //tmp 文件内容
    // 关闭文件 
    file.Close();  
    sEssary sessary;
    HTREEITEM selItem;
    for(map<HTREEITEM, sEssary>::iterator it = m_itreeData.begin(); it != m_itreeData.end(); it++)
    {

        if(it->second.NovelName==WenJianMing)
        {
            MessageBox(_T("该文件已存在"));
            return;
        }
    }
    for(map<HTREEITEM, sEssary>::iterator it = m_itreeData.begin(); it != m_itreeData.end(); it++)
    {
        if(it->second.CategoryName==DiZhi)
        {
            sessary.CategoryName = DiZhi;
            sessary.ContenEN = tmp;
            sessary.NovelName = WenJianMing;

            selItem=m_Tree.InsertItem(WenJianMing, 1, 3, it->second.hParent, TVI_LAST);
            sessary.hParent = it->second.hParent;
            m_itreeData.insert(make_pair(selItem,sessary));
            return;
        }
    }
    sessary.CategoryName = DiZhi;
    sessary.ContenEN = tmp;
    sessary.NovelName = WenJianMing;
    HTREEITEM hArtItem;  // 可表示任一文章节点的句柄  
    m_Tree.SetItemData(hCataItem1, 1);
    hArtItem = m_Tree.InsertItem(DiZhi, 1, 2, hCataItem1, TVI_LAST);
    sessary.hParent = hArtItem;

    //获得选择项
    //selItem = m_Tree.GetSelectedItem();
    selItem=m_Tree.InsertItem(WenJianMing, 1, 3, hArtItem, TVI_LAST);
    m_itreeData.insert(make_pair(selItem,sessary));
}

void CAudiobooks::MyExpandTree(HTREEITEM hTreeItem)  
{  
    if(!m_Tree.ItemHasChildren(hTreeItem))  
    {  
        return;  
    } 

    HTREEITEM hNextItem = m_Tree.GetChildItem(hTreeItem);  
    /*while (hNextItem != NULL)  
    { 

    MyExpandTree(hNextItem);  
    hNextItem = m_Tree.GetNextItem(hNextItem, TVGN_NEXT);  
    }*/

    m_Tree.Expand(hTreeItem,TVE_EXPAND);	
}  

//转成 MP3
void CAudiobooks::OnBnClickedButton5()
{
    // TODO: 在此添加控件通知处理程序代码
    //生成WAV文件
    int iStart = 0;
    int iEnd = 0;
    CString strContent;

    //获取选中信息
    ((CEdit*)(GetDlgItem(IDC_AUDIOBOOKEDIT)))->GetSel(iStart, iEnd);
    GetDlgItemText(IDC_AUDIOBOOKEDIT,strContent);
    if (iStart == iEnd)
    {
        MessageBox(_T("请选中文本框中相关信息，然后再尝试转换为MP3。"), _T("提示"), 0);
        return;
    }
    CString strInfo = strContent.Right(strContent.GetLength() - iStart);
    strInfo.Truncate(iEnd - iStart);

    theApp.StopSpeak();
    //theApp.StopWaveRecordReco();
    theApp.SpeechRecognition_Stop(theApp.m_strCommonWaveFile);

    CFileDialog dlgmp3(FALSE, _T("mp3"), NULL,
        OFN_ENABLESIZING | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_EXPLORER | OFN_NONETWORKBUTTON,
        _T("mp3文件(*.mp3)|*.mp3||"), CWnd::FromHandle(GetSafeHwnd()));
    dlgmp3.m_ofn.hwndOwner = GetSafeHwnd();
    OPENFILENAME& ofn = dlgmp3.GetOFN();
    TCHAR tbuf[4096];
    tbuf[0] = _T('\0');
    ofn.lpstrFile = tbuf;
    ofn.nMaxFile = _countof(tbuf);
    if (dlgmp3.DoModal() != IDOK)
    {
        return;
    }
    CString strMp3 = dlgmp3.GetPathName();
    ::DeleteFile(strMp3);
    CString strWav = dlgmp3.GetPathName().Left(strMp3.GetLength() - strlen("wav"));
    strWav += _T("wav");
    ::DeleteFile(strWav);
    SplitResultVector sptToVoice;
    SplitString(TString(strInfo), _T("\r\n"), sptToVoice);
    SplitResultVector::const_iterator p;
    int i = 0;
    theApp.SpeakBindToFile(strWav);

    for (p = sptToVoice.begin(); p != sptToVoice.end(); ++p)
    {
        if (p->empty())
        {
            continue;
        }
        //获取朗读者
        CString strLangDuZhe;
        GetDlgItemText(IDC_COMBO1, strLangDuZhe);
        if (!strLangDuZhe.IsEmpty())
        {
            //获取朗读速度
            int iSpeed = GetScrollPos(IDC_SCROLLBAR1);
            CString strSpeed;
            strSpeed.Format(_T("%d"), iSpeed);
            //MyAfxMessageBox(_T("strspeed %s"), strSpeed);
            theApp.SetVoiceRateByValue(strLangDuZhe, strSpeed);
        }

        i++;
        theApp.SpeakAndWait(p->c_str());
    }
    theApp.SpeakRestore();
    theApp.hlpWave2Mp3(strWav, strMp3);	
}

void CAudiobooks::SetButtonStatus(int iButtonId, BOOL bStatus)
{
    CRect MyRect;
    GetDlgItem(iButtonId)->EnableWindow(bStatus);
    ((CGdipButton*)GetDlgItem(iButtonId))->EnableButton(bStatus);
    GetDlgItem(iButtonId)->GetClientRect(&MyRect);
    ValidateRect(MyRect);
    return;
}

void CAudiobooks::GetSentencesFromPaper()
{
    CString strTempOne;
    m_ReadInfoVec.clear();

    int iPos = 0;
    CString strInfo;
    GetReadInfo(iPos, strInfo);

    if(strInfo == _T(""))
    {
        MessageBox(_T("请选择跟读内容"),_T("提示"));
        return;
    }

    char*pstr1 ;
    pstr1 = (LPSTR)(LPCTSTR)strInfo; 
    for(int i = 0; i < strInfo.GetLength(); i++)
    {
        if((strInfo[i] == '.') || (strInfo[i] == '?') || (strInfo[i] == '!') || (strInfo[i] == ';'))
        {
            strTempOne.Trim();
            if (!strTempOne.IsEmpty())
            {
                m_ReadInfoVec.push_back(strTempOne);
            }

            strTempOne = _T("");
            continue;
        }
        strTempOne += strInfo[i];
    }

    if(strTempOne != _T(""))
    {
        strTempOne.Trim();
        m_ReadInfoVec.push_back(strTempOne);
        strTempOne = "";
    }

    m_iReadInfoIndex = 0;

}

//跟读
void CAudiobooks::OnBnClickedButton26()
{
    // TODO: 在此添加控件通知处理程序代码
    m_nReadMode = E_FOLLOWME_SENT;

    int n = 0;
    Invalidate();
    theApp.m_pSpVoice->Resume();

    CString strTempOne;
    m_ReadInfoVec.clear();
    JinDuTiao1 = TRUE;
    /*GetDlgItem(IDC_BUTTON25)->EnableWindow(TRUE);
    m_chongfugendu.EnableButton(TRUE);*/


    CRect MyRect;

    SetButtonStatus(IDC_BUTTON22, TRUE);
    SetButtonStatus(IDC_BUTTON25, FALSE);
    SetButtonStatus(IDC_BUTTON26, FALSE);
    SetButtonStatus(IDC_BUTTON21, FALSE);

    SetListenRelatedButtonStatus(FALSE);

    int iPos = 0;
    CString strInfo;
    GetReadInfo(iPos, strInfo);

    if(strInfo == _T(""))
    {
        MessageBox(_T("请选择跟读内容"),_T("提示"));
        return;
    }

    char*pstr1 ;
    pstr1 = (LPSTR)(LPCTSTR)strInfo; 
    for(int i = 0; i < strInfo.GetLength(); i++)
    {
        if((strInfo[i] == '.') || (strInfo[i] == '?') || (strInfo[i] == '!') || (strInfo[i] == ';'))
        {
            strTempOne.Trim();
            if (!strTempOne.IsEmpty())
            {
                m_ReadInfoVec.push_back(strTempOne);
            }
            
            strTempOne = _T("");
            continue;
        }
        strTempOne += strInfo[i];
    }

    if(strTempOne != _T(""))
    {
        strTempOne.Trim();
        m_ReadInfoVec.push_back(strTempOne);
        strTempOne = "";
    }

    CString strSuDu;
    int iSpead = m_readspeedscrollbar.GetScrollPos( ) - 10;
    strSuDu.Format(_T("%d"), iSpead);
    CString strLangDuZhe;
    GetDlgItemText(IDC_COMBO1, strLangDuZhe);

    theApp.SetVoiceRateByValue(strLangDuZhe, strSuDu);

    m_iReadInfoIndex = 0;

    CString tmp;
    if (!m_ReadInfoVec[m_iReadInfoIndex].IsEmpty())
    {
        tmp = m_ReadInfoVec[m_iReadInfoIndex];
        str_GenDu = m_ReadInfoVec[m_iReadInfoIndex];
        m_strChongFuGenDu = (CString)m_ReadInfoVec[m_iReadInfoIndex];
        theApp.Speak(m_ReadInfoVec[m_iReadInfoIndex]);			
    }
    AudioBookKillTimer();

    //int iSecond = GetPauseMSecond();
    //SetTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD, iSecond, NULL);
}

void CAudiobooks::AudioBookKillTimer()
{
    KillTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD);
    KillTimer(TIMER_AUDIO_BOOK_RECORD);
    KillTimer(TIMER_AUDIO_BOOK_MARK_SENTENCE);
    KillTimer(TIMER_AUDIO_BOOK_INTERVAL);
    KillTimer(TIMER_AUDIO_BOOK_PLAY);
    KillTimer(TIMER_AUDIO_BOOK_READ_END);
}

//结束
void CAudiobooks::OnBnClickedButton22()
{	
    AudioBookKillTimer();

    theApp.StopSpeak();

    SetDlgItemText(IDC_STATIC222, _T(""));

    m_JinDuTiao.SetPos(0);

    JinDuTiao1 = FALSE;

    Invalidate();

    //跟读
    SetButtonStatus(IDC_BUTTON26, TRUE);

    //重复跟读
    SetButtonStatus(IDC_BUTTON25, TRUE);

    //结束
    SetButtonStatus(IDC_BUTTON22, FALSE);

    //播放录音
    SetButtonStatus(IDC_BUTTON21, m_bIsRecorded);

    GetDlgItem(IDC_PROGRESS1)->ShowWindow(SW_HIDE);
    GetDlgItem(IDC_STATIC222)->ShowWindow(SW_HIDE);

    SetListenRelatedButtonStatus(TRUE);

    CString MsgInfo;
    m_Edit.GetWindowText(MsgInfo);
    MsgInfo.Replace(_T("\r\n"), _T(" "));
    if (m_ReadInfoVec.size() > 0)
    {
        int iPos = MsgInfo.Find(m_ReadInfoVec[m_iReadInfoIndex]);
        m_Edit.SetSel(iPos, iPos+m_ReadInfoVec[m_iReadInfoIndex].GetLength());
        SetRichEditSelColor(&m_Edit, RGB(0,0,0));
        m_Edit.SetSel(-1, 0);
    }
    
}

//录音回放
void CAudiobooks::OnBnClickedButton21()
{
    // TODO: 在此添加控件通知处理程序代码

    m_nReadMode = E_PLAY_RECORD;

    //跟读
    SetButtonStatus(IDC_BUTTON26, FALSE);

    //重复跟读
    SetButtonStatus(IDC_BUTTON25, FALSE);

    SetButtonStatus(IDC_BUTTON21, m_bIsRecorded);
    

    if (TRUE != theApp.AudioRecordPlay(GetSafeHwnd()))
    {
        //跟读
        SetButtonStatus(IDC_BUTTON26, TRUE);

        //重复跟读
        SetButtonStatus(IDC_BUTTON25, TRUE);

        MyAfxMessageBox(_T("播放录音文件 %s 失败"), theApp.m_strRecordFile);
    }

    Invalidate();

    //SetListenRelatedButtonStatus(FALSE);
    //SetTimer(TIMER_AUDIO_BOOK_PLAY, m_iRecordMs + 200, NULL); //多加 200ms，确保录音播放完毕
    return;
}

void CAudiobooks::OnCbnSelchangeZiTi()
{
    // TODO: 在此添加控件通知处理程序代码
    //字体变动，重新写文本框的信息，使按照选中的字体，字号来显示
    OnChangeZitiOrZiHao();
}


void CAudiobooks::OnChangeZitiOrZiHao()
{
    CString strZiTi;

    m_fontstylecombo.GetLBText(m_fontstylecombo.GetCurSel(), strZiTi);
    //GetDlgItemText(IDC_MFCFONTCOMBO1, strZiTi);
    //下面的这些字体可能使文章显示乱码，用户选择时给出提示
    bool bIsInValidZiTi = (strZiTi.Find(_T("04b_21")) != (-1)) || (strZiTi.Find(_T("Marlett")) != (-1)) || (strZiTi.Find(_T("MT Extra")) != (-1)) 
        || (strZiTi.Find(_T("Wingdings")) != (-1)) || (strZiTi.Find(_T("MS reference")) != (-1)) || (strZiTi.Find(_T("Symbol")) != (-1)) || (strZiTi.Find(_T("Webding")) != (-1));

    if (bIsInValidZiTi)
    {
        MyAfxMessageBox(_T("选择的字体可能使文章信息无法查看，请重新选择！"));
        return;
    }

    UINT iZiHao;
    CString strZiHao;
    m_zihaocombox.GetLBText(m_zihaocombox.GetCurSel(), strZiHao);

    iZiHao = _ttoi(strZiHao);
    //MyAfxMessageBox(_T("字号：%d"), iZiHao);

    CString strContent;
    GetDlgItemText(IDC_AUDIOBOOKEDIT, strContent);
    m_editFont.Detach();
    m_editFont.CreatePointFont(iZiHao*10, strZiTi);

    GetDlgItem(IDC_AUDIOBOOKEDIT)->SetFont(&m_editFont); 
    SetDlgItemText(IDC_AUDIOBOOKEDIT, strContent.GetString());

    UpdateWindow();
}

void CAudiobooks::OnCbnSelchangeZiHao()
{
    // TODO: 在此添加控件通知处理程序代码
    //字号变动，重新写文本框的信息，使按照选中的字体，字号来显示
    OnChangeZitiOrZiHao();
}

void CAudiobooks::OnBnClickedButton8()
{
    // TODO: 在此添加控件通知处理程序代码
    OnBnClickedButton22();

    CRecite recite;
    CString strEdit;
    GetDlgItemText(IDC_AUDIOBOOKEDIT, strEdit); // 获取指定ID的编辑框内容

    recite.m_strEdit = strEdit;
    recite.DoModal();
}

//重复
void CAudiobooks::OnBnClickedButton18()
{
    OnBnClickedButton19(); //用朗读的代码
}

// 重复跟读
void CAudiobooks::OnBnClickedButton25()
{
    if (m_nReadMode != E_FOLLOWME_NEXT_SENT)
    {
        GetSentencesFromPaper();
        
        m_nReadMode = E_FOLLOWME_NEXT_SENT;
    } 
    else
    {
        ++m_iReadInfoIndex;
    }

    Invalidate();
    SetButtonStatus(IDC_BUTTON25, FALSE);
    SetButtonStatus(IDC_BUTTON26, FALSE);
    SetButtonStatus(IDC_BUTTON21, FALSE);
    SetButtonStatus(IDC_BUTTON22, TRUE);
    SetListenRelatedButtonStatus(FALSE);
    UpdateWindow();

    CString tmp = m_ReadInfoVec[m_iReadInfoIndex];
    tmp = tmp.Trim(_T(" "));
    if ((!tmp.IsEmpty()) && (tmp.GetLength() > 1))
    {
        str_GenDu = m_ReadInfoVec[m_iReadInfoIndex];
        m_strChongFuGenDu = (CString)m_ReadInfoVec[m_iReadInfoIndex];
        theApp.StopSpeak();
        theApp.Speak(m_ReadInfoVec[m_iReadInfoIndex]);	
    }
    else
    {
        return;
    }

    AudioBookKillTimer();	

    //SetTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD, GetPauseMSecond(), NULL);
}


void CAudiobooks::OnBnClickedButton10()
{
    // TODO: 在此添加控件通知处理程序代码
}

int CAudiobooks::GetPauseMSecond()
{
    int iSecond = 0;
    iSecond = (m_ReadInfoVec[m_iReadInfoIndex].GetLength()/25);
    if (iSecond == 0)
    {
        iSecond = 1;
    }
    iSecond = (iSecond*2 + 1)*1000;

    return iSecond;
}

void CAudiobooks::RefreshStaticText(const int iStaticIndex)
{
    CRect rc;
    GetDlgItem(iStaticIndex)->GetWindowRect(&rc);
    //转换为相对坐标
    ScreenToClient(&rc);
    //刷新指定区域,注意第2个参数为真,即刷新背景
    InvalidateRect(&rc,TRUE);
}

void CAudiobooks::OnTimer(UINT_PTR nIDEvent)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值
    //int nstart,nEnd;
    int LineNum = 10;
    CString strZiHao;
    m_zihaocombox.GetLBText(m_zihaocombox.GetCurSel(), strZiHao);
    CString strBadWord;
    CString MsgInfo;
    int iPos = 0;

    CString tmp;
    switch (nIDEvent)
    {
    case TIMER_AUDIO_BOOK_On_Read:			
        All_i+= LineNum;
        m_Edit.LineScroll(All_i);	
        break;
    case TIMER_AUDIO_BOOK_BEFORE_RECORD:
        SetButtonStatus(IDC_BUTTON21, m_bIsRecorded);
        m_bIsRecorded = FALSE;
        KillTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD);

        //SetDefautCharFormat();
        //m_Edit.SetSelectionCharFormat(m_cfDefault);
        //m_Edit.GetWindowTextW(MsgInfo);
        //iPos = MsgInfo.Find(m_ReadInfoVec[m_iReadInfoIndex]);
        //((CEdit*)GetDlgItem(IDC_AUDIOBOOKEDIT))->SetSel(0, iPos + m_ReadInfoVec[m_iReadInfoIndex].GetLength(), true);

        m_iRecordMs = GetPauseMSecond();
        m_iMaxRange = m_iRecordMs / 1000;
        GetDlgItem(IDC_STATIC222)->ShowWindow(TRUE);
        GetDlgItem(IDC_PROGRESS1)->ShowWindow(TRUE);

        m_JinDuTiao.SetRange(0, m_iMaxRange);
        m_JinDuTiao.SetStep(1);
        m_JinDuTiao.SetPos(0);
        m_iProcess = 0;
        theApp.PlayDingMusic();	

        SetDlgItemText(IDC_STATIC222, _T("正在录音"));
        RefreshStaticText(IDC_STATIC222);
        theApp.SpeechRecognition_Start();

        //TRACE(_T("m_iMaxRange:%d GetPauseMSecond return:%d"), m_iMaxRange, GetPauseMSecond());

        SetTimer(TIMER_AUDIO_BOOK_RECORD, 1000, NULL);
        //UpdateData(TRUE);

        break;
    case TIMER_AUDIO_BOOK_RECORD:
        ++m_iProcess;
        m_JinDuTiao.StepIt();
        if (m_iProcess == m_iMaxRange)
        {
            KillTimer(TIMER_AUDIO_BOOK_RECORD);
            theApp.SpeechRecognition_Stop(theApp.m_strCommonWaveFile);
            //m_playsound.EnableButton(TRUE);
            m_bIsRecorded = TRUE;
            SetDlgItemText(IDC_STATIC222, _T("录音结束....."));
            m_iMaxRange = (GetPauseMSecond()/1000)/2;
            m_JinDuTiao.SetRange(0,m_iMaxRange);
            m_JinDuTiao.SetStep(1);
            m_JinDuTiao.SetPos(0);

            SetTimer(TIMER_AUDIO_BOOK_MARK_SENTENCE, 1000, NULL);
            theApp.SpeechRecognitionCompare2(m_ReadInfoVec[m_iReadInfoIndex], MsgInfo, CTeacherManagerApp::ct_sent );
            m_iProcess = 0;
        }
        break;
    case TIMER_AUDIO_BOOK_MARK_SENTENCE:
        SetDlgItemText(IDC_STATIC222, _T("正在打分....."));
        m_JinDuTiao.StepIt();
        ++m_iProcess;
        if (m_iProcess == m_iMaxRange)
        {
            KillTimer(TIMER_AUDIO_BOOK_MARK_SENTENCE);
            CString strScore = theApp.m_strRecognitionCompare[8].GetString();
            if (strScore.IsEmpty())
            {
                strScore = _T("0");
            }

            if (theApp.m_strRecognitionCompare[7].IsEmpty())
            {
                strBadWord.Format(_T("得分:%s分"), strScore);
            }
            else
            {
                strBadWord.Format(_T("得分:%s分"), strScore);
            }

            SetDlgItemText(IDC_STATIC222, strBadWord);
            

            CString MsgInfo;
            m_Edit.GetWindowText(MsgInfo);
            MsgInfo.Replace(_T("\r\n"), _T(" "));
            int iPos = MsgInfo.Find(m_ReadInfoVec[m_iReadInfoIndex]);
            m_Edit.SetSel(iPos, iPos+m_ReadInfoVec[m_iReadInfoIndex].GetLength());
            SetRichEditSelColor(&m_Edit, RGB(0,0,0));
            m_Edit.SetSel(-1, 0);

            if (m_nReadMode != E_FOLLOWME_NEXT_SENT)
            {
                SetTimer(TIMER_AUDIO_BOOK_INTERVAL, 1000, NULL);
            } 
            else 
            {
                Invalidate();
                SetButtonStatus(IDC_BUTTON21, m_bIsRecorded); //播放录音
                SetButtonStatus(IDC_BUTTON25, TRUE); //跟读
                SetButtonStatus(IDC_BUTTON26, TRUE); //重复跟读
                SetButtonStatus(IDC_BUTTON22, FALSE);
                SetListenRelatedButtonStatus(TRUE);
                GetDlgItem(IDC_STATIC222)->ShowWindow(SW_HIDE);
            }

        }

        break;
    case TIMER_AUDIO_BOOK_INTERVAL:
        ++m_iReadInfoIndex;
        KillTimer(TIMER_AUDIO_BOOK_INTERVAL);

        if (m_ReadInfoVec.size() > (UINT)m_iReadInfoIndex)
        {
            tmp = m_ReadInfoVec[m_iReadInfoIndex];
            tmp = tmp.Trim(_T(" "));
            if ((!tmp.IsEmpty()) && (tmp.GetLength() > 1))
            {
                str_GenDu = m_ReadInfoVec[m_iReadInfoIndex];
                m_strChongFuGenDu = (CString)m_ReadInfoVec[m_iReadInfoIndex];
                theApp.Speak(m_ReadInfoVec[m_iReadInfoIndex]);
                //SetTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD, GetPauseMSecond(), NULL);
            }
        }
        else
        {
            Invalidate();
            //SetButtonStatus(IDC_BUTTON21, TRUE); //播放录音
            SetButtonStatus(IDC_BUTTON25, TRUE); //跟读
            SetButtonStatus(IDC_BUTTON26, TRUE); //重复跟读
            SetButtonStatus(IDC_BUTTON22, FALSE);
            SetListenRelatedButtonStatus(TRUE);
            GetDlgItem(IDC_STATIC222)->ShowWindow(SW_HIDE);
        }
        break;
    case TIMER_AUDIO_BOOK_PLAY:
        KillTimer(TIMER_AUDIO_BOOK_PLAY);

        //跟读
        SetButtonStatus(IDC_BUTTON26, TRUE);

        //重复跟读
        SetButtonStatus(IDC_BUTTON25, TRUE);

        SetListenRelatedButtonStatus(TRUE);
        SetButtonStatus(IDC_BUTTON22, FALSE);
        break;
    case TIMER_AUDIO_BOOK_READ_END:
        Invalidate();
        SetButtonStatus(IDC_BUTTON19, TRUE);
        SetButtonStatus(IDC_BUTTON18, TRUE);
        SetButtonStatus(IDC_BUTTON5, TRUE);
        SetButtonStatus(IDC_BUTTON6, FALSE);

        SetReadRelatedButtonStatus(TRUE);	
        break;
    default:
        break;
    }
    CDialogEx::OnTimer(nIDEvent);
}

//删除选中的素材
void CAudiobooks::OnBnClickedButtonDelFile()
{
    // TODO: 在此添加控件通知处理程序代码
    HTREEITEM Item = m_Tree.GetSelectedItem();
    HTREEITEM ParentItem = m_Tree.GetParentItem(Item);
    //获取父节点的文字
    CString strItemName = m_Tree.GetItemText(ParentItem);
    if ((strItemName.Find(_T(":")) == (-1)) && (strItemName.Compare(_T("素材库")) != 0))
    {
        MyAfxMessageBox(_T("只能对自己添加的文章删除。"));
        return;
    }

    strItemName = m_Tree.GetItemText(Item);
    if (strItemName.Compare(_T("添加我的素材库")) == 0)
    {
        MyAfxMessageBox(_T("不能删除 添加我的素材库 节点。"));
        return;
    }

    if(Item == NULL)
    {
        MyAfxMessageBox(_T("请在窗口左边的树控件的素材库节点下选择自己添加的文章节点，然后再试，谢谢！"));
        return;
    }
    else if(m_Tree.ItemHasChildren(Item))
    {
        CString strMessage=_T("当前选择的节点下面有多个文章，是否删除?");
        if(MessageBox(strMessage,_T(""),MB_YESNO)== IDYES)
        {
            EraseTreeIterInfo(Item);
            //m_Tree.DeleteItem(Item);//删除子树
            if (!m_Tree.ItemHasChildren(ParentItem))
            {
                EraseTreeIterInfo(ParentItem);
                //m_Tree.DeleteItem(ParentItem);//删除子树
            }
        }
    }
    else
    {
        EraseTreeIterInfo(Item);
        //m_Tree.DeleteItem(Item);
    }


    return;
}

void CAudiobooks::EraseTreeIterInfo(HTREEITEM Item)
{
    auto Iter = m_itreeData.find(Item);
    int isize = m_itreeData.size();
    HTREEITEM currentItem = NULL;

    CString strName;
    if (Iter != m_itreeData.end())
    {
        int nRet = MessageBox(_T("是否删除当前文章？"), _T("提示"), MB_YESNO);
        if (nRet == IDYES)
        {
            m_itreeData.erase(Iter);
            m_Tree.DeleteItem(Item);
            SetDlgItemText(IDC_AUDIOBOOKEDIT, _T(""));
            currentItem = m_Tree.GetSelectedItem();
            strName = m_Tree.GetItemText(currentItem);
            for(map<HTREEITEM, sEssary>::iterator it = m_itreeData.begin(); it != m_itreeData.end(); it++)
            {

                if(it->first == currentItem)
                    //if( it->second.NovelName.compare(NovelName)==0)
                {
                    CString  str = it->second.ContenEN;

                    GetDlgItem(IDC_AUDIOBOOKEDIT)->SetWindowText(str.GetString());   //EDIT控件显示数据
                    return;
                }
            }
        } 
    }
}

void CAudiobooks::SetReadRelatedButtonStatus(BOOL bButtonStatus)
{
    Invalidate();
    SetButtonStatus(IDC_BUTTON25, bButtonStatus);
    SetButtonStatus(IDC_BUTTON26, bButtonStatus);
    SetButtonStatus(IDC_BUTTON21, m_bIsRecorded);
    SetButtonStatus(IDC_BUTTON22, FALSE);
}

void CAudiobooks::SetListenRelatedButtonStatus(BOOL bButtonStatus)
{
    Invalidate();
    SetButtonStatus(IDC_BUTTON18, bButtonStatus);
    SetButtonStatus(IDC_BUTTON19, bButtonStatus);
    SetButtonStatus(IDC_BUTTON5, bButtonStatus); //转换成MP3
    SetButtonStatus(IDC_BUTTON6, FALSE); //停止
}


void CAudiobooks::OnNMClickTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
    // TODO: Add your control notification handler code here

    POINT point;
    GetCursorPos(&point);//获得鼠标点击的位置
    m_Tree.ScreenToClient(&point);//转化为客户坐标
    UINT uFlags;
    HTREEITEM CurrentItem;
    CurrentItem = m_Tree.HitTest(point, &uFlags);//获得当前点击节点的ITEM
    CString NovelName = m_Tree.GetItemText(CurrentItem);
    if(NovelName == _T("添加我的素材库"))
    {
        //添加打开素材库的代码
        OnBnClickedButton7();
    }

    *pResult = 0;
}

void CAudiobooks::SetRichEditSelColor(CRichEditCtrl* pREdt, COLORREF rgb)
{
    CHARFORMAT2 cf;
    cf.cbSize = sizeof(cf);

    //pREdt->GetSelectionCharFormat(cf);
    //cf.crTextColor = rgb;
    //cf.dwMask |= CFM_COLOR;
    //pREdt->SetSelectionCharFormat(cf);

    pREdt->GetSelectionCharFormat(cf);
    //cf.dwMask = CFM_STRIKEOUT|CFM_BOLD;
    //cf.dwEffects = CFM_BOLD;
    cf.crTextColor = rgb;
    cf.dwMask = CFM_COLOR;
    cf.dwEffects = 0;
    pREdt->SetSelectionCharFormat(cf);
}


LRESULT CAudiobooks::OnTTSHandleEvent(WPARAM wParam, LPARAM lParam)
{
    CSpEvent        event;  // helper class in sphelper.h for events that releases any 
    // allocated memory in it's destructor - SAFER than SPEVENT
    SPVOICESTATUS   Stat;
    HRESULT         hr = S_OK;
    WPARAM          nStart;
    LPARAM          nEnd;
    while( event.GetFrom(theApp.m_pSpVoice) == S_OK )
    {
        switch ( event.eEventId )
        {
        case SPEI_START_INPUT_STREAM:
            break;
        case SPEI_END_INPUT_STREAM:
            theApp.m_pSpVoice->GetStatus(&Stat, NULL);
            TRACE(_T("recv SPEI_END_INPUT_STREAM, dwRunningState:%d\n"), Stat.dwRunningState);
            //点击停止导致发送的End_Stream，什么也不干
            if ((Stat.dwRunningState & SPRS_IS_SPEAKING) == 0)
            {
                TRACE(_T("StopSpeak?\n"));
                break;
            }
            //OnBnClickedButton6();
            m_Edit.SetSel(-1, 0);
            if (E_FOLLOWME_SENT == m_nReadMode || E_FOLLOWME_NEXT_SENT == m_nReadMode)
            {
                SetTimer(TIMER_AUDIO_BOOK_BEFORE_RECORD, 500, NULL);
            }
            
            break;
        case SPEI_VOICE_CHANGE:
            break;

        case SPEI_TTS_BOOKMARK:
            break;

        case SPEI_WORD_BOUNDARY:
            {
                hr = theApp.m_pSpVoice->GetStatus( &Stat, NULL );
                if( FAILED( hr ) )
                {
                    TRACE(_T("Voice GetStatus error\r\n"));
                    break;
                }
                nStart = Stat.ulInputWordPos + m_nReadCurrentCursor;
                nEnd = nStart + Stat.ulInputWordLen;
                m_Edit.SetSel(nStart, nEnd);    
            }
            break;

        case SPEI_PHONEME:
            break;

        case SPEI_VISEME:				
            break;

        case SPEI_SENTENCE_BOUNDARY:
            {
                hr = theApp.m_pSpVoice->GetStatus( &Stat, NULL );
                if( FAILED( hr ) )
                {
                    TRACE(_T("Voice GetStatus error\r\n"));
                    break;
                }

                if (E_FOLLOWME_SENT == m_nReadMode || E_FOLLOWME_NEXT_SENT == m_nReadMode)
                {
                    nStart = Stat.ulInputSentPos + m_nReadCurrentCursor;
                    nEnd = nStart + Stat.ulInputSentLen;
  
                    CString MsgInfo;
                    m_Edit.GetWindowText(MsgInfo);
                    MsgInfo.Replace(_T("\r\n"), _T(" "));
                    int iPos = MsgInfo.Find(m_ReadInfoVec[m_iReadInfoIndex]);
                    m_nReadCurrentCursor = iPos;
                    m_Edit.SetSel(iPos, iPos+m_ReadInfoVec[m_iReadInfoIndex].GetLength());
                    SetRichEditSelColor(&m_Edit, RGB(255,0,0));
                }
            }
            break;
        case SPEI_TTS_AUDIO_LEVEL:
            break;

        case SPEI_TTS_PRIVATE:
            break;

        default:
            TRACE( _T("Unknown message:%d\n"), event.eEventId );
            break;
        }
    }

    return 0L;
}

LRESULT CAudiobooks::OnMciNotify(WPARAM wParam,LPARAM lParam)
{
    if(MCI_NOTIFY_SUCCESSFUL == wParam)
    {
        if (E_PLAY_RECORD == m_nReadMode)
        {
            OnBnClickedButton22();
        }
    }

    return 0L;
}